import { message, Modal, Tree } from 'antd';
import { useEffect, useState } from 'react';
import an58 from '@mmstudio/an000058';
import Button from '../../../components/button';
import { d2n, tree } from '../menu/content';
import { Message as M2, Result as R2 } from '../../api/admin/role/menus/save.api';
import api from '../../../atoms/api';
import { Message as M1, Result as R1 } from '../../api/admin/role/menus/getuserole.api';

export default function Menus({
	role,
	menus
}: {
	role: ITbfdrole;
	menus: ITbfdmenu[];
}) {
	const [visible, setvisible] = useState(false);
	const [confirmLoading, setConfirmLoading] = useState(false);
	const treenodes = tree(menus);
	const data = treenodes.map(d2n);
	const [checkedKeys, setcheckedKeys] = useState([] as string[]);
	useEffect(() => {
		void (async () => {
			const ids = await an58<R1, M1>(api['/api/admin/role/menus/getuserole'], 'get', {
				roleid: role.roleid
			});
			setcheckedKeys(ids);
		})();
	}, []);
	return <>
		<a onClick={() => {
			setvisible(true);
		}}>菜单分配</a>
		<Modal confirmLoading={confirmLoading} title={'分配菜单'} maskClosable visible={visible} onCancel={() => {
			setConfirmLoading(false);
			setvisible(false);
		}} footer={null} >
			<div className='tree'>
				<Tree
					showIcon
					multiple={false}
					checkable
					checkStrictly
					checkedKeys={checkedKeys}
					onCheck={(keys) => {
						setcheckedKeys((keys as {
							checked: string[];
							halfChecked: string[];
						}).checked);
						console.log(keys);
					}}
					defaultExpandAll
					treeData={data}
				/>
			</div>
			<div className='footer'>
				<Button onClick={async () => {
					const ret = await an58<R2, M2>(api['/api/admin/role/menus/save'], 'put', {
						roleid: role.roleid,
						menuids: checkedKeys
					});
					if (ret.ok === true) {
						message.success('保存成功');
					} else {
						message.error(ret.message);
					}
				}}>保存</Button>
			</div>
		</Modal>
		<style jsx>{`
.tree{
	display: block;
	width: 100%;
	height: 60vh;
}
.footer{
	display: flex;
	justify-content: center;
	background-color: #eee;
	padding: 1rem;
}
`}</style>
	</>;
}
